<template>
	<div>
		<el-form label-width="150px" :model="form" ref="ruleForm" :rules="rules" :inline-message="true">
			<div class="container">
				<h3 class="margin_b_20">商品视频&商品图</h3>
				<div class="dflex">
					<div>
						<el-form-item>
							<div class="video crpr dflex_c" @click="choiceVideo">
								<div v-if="!video.poster" class="iconfont icon24gf-play"></div>
								<div v-else class="wh100">
									<img :src="video.poster" class="wh100" style="object-fit: cover;border-radius: 5px;"
										@click.stop="playVideo(video.url)" />
									<div class="iconfont iconbofang pos_a" @click.stop="playVideo(video.url)"></div>
									<div class="del_btn_box dflex_c pos_a" @click.stop="posterDelete">
										<div class="del_btn"></div>
										<div class="del_btn pos_a"></div>
									</div>
									<div class="duration lh_initial pos_a" @click.stop="playVideo(video.url)">
										{{ secToTime(video.duration) }}</div>
								</div>
							</div>
						</el-form-item>
					</div>
					<div>
						<el-form-item label=" " label-width="80px" prop="imageValue" ref="validImg">
							<uni-file-picker ref="imageValue" v-model="form.imageValue" fileMediatype="image" limit="5"
								returnType="array" :image-styles="imageStyle" @success="imgUpload" @delete="imgDelete"
								@move="imgMove" />
						</el-form-item>
					</div>
				</div>
			</div>
			<div class="container">
				<h3 class="margin_b_20">商品详情</h3>
				<el-form-item label=" " prop="editorContent" ref="editorContent">
					<use-editor ref="editor" @editorChange="editorChange"></use-editor>
				</el-form-item>
			</div>
		</el-form>
		<el-dialog class="video_dialog" top="12vh" width="70%" append-to-body :visible.sync="videoDialog"
			@open="dialogOpen" @opened="dialogOpened" @closed="dialogClosed" v-dialogDrag>
			<video-player v-if="isVideo" class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true"
				:options="playerOptions"></video-player>
		</el-dialog>
	</div>
</template>

<script>
	import '@/common/video.css';
	export default {
		data() {
			return {
				form: {
					imageValue: [],
					editorContent: ''
				},
				imageStyle: {
					height: '150px',
					width: '150px'
				},
				rules: {
					imageValue: [{
						type: 'array',
						required: true,
						message: '请上传主图',
						trigger: 'change'
					}],
					editorContent: [{
						required: true,
						message: '请绘制商品详情',
						trigger: 'change'
					}]
				},
				video: {},
				videoDialog: false,
				isVideo: false,
				playerOptions: {
					playbackRates: [0.1, 0.3, 0.5, 1.0, 3.0, 5.0, 10.0], //可选择的播放速度
					autoplay: false, //如果true,浏览器准备好时开始播放。
					muted: false, // 默认情况下将会消除任何音频。
					loop: false, // 视频一结束就重新开始。
					preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
					language: 'zh-CN',
					aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
					fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
					sources: [{
						type: '',
						src: '' //url地址
					}],
					poster: '', //你的封面地址
					notSupportedMessage: '此视频暂无法播放', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
					controlBar: {
						timeDivider: true, //当前时间和持续时间的分隔符
						durationDisplay: true, //显示持续时间
						remainingTimeDisplay: false, //是否显示剩余时间功能
						fullscreenToggle: true //全屏按钮
					}
				}
			};
		},
		methods: {
			submitData(callback) {
				if (this.form.editorContent == '<p><br></p>') {
					this.form.editorContent = '';
				}
				this.$refs.ruleForm.validate((valid, obj) => {
					this.$api.set_unvalidated_form_focus(this, obj);
					if (valid) {
						if (typeof callback === 'function') {
							callback({
									content: this.form.editorContent,
									imgs: this.form.imageValue,
									video: this.video
								},
								valid
							);
						}
					} else {
						if (typeof callback === 'function') {
							callback({
									content: this.form.editorContent,
									imgs: this.form.imageValue,
									video: this.video
								},
								valid
							);
						}
						return false;
					}
				});
			},
			getData(callback) {
				this.submitData(callback);
			},
			setData(data) {
				this.video = data.video || {};
				this.form.imageValue = data.imgs;

				if (data.content) {
					this.form.editorContent = data.content;
					this.$refs.editor.setContent(this.form.editorContent);
				}
			},
			editorChange(res) {
				this.form.editorContent = res;
				if (res == '') {
					this.$refs.ruleForm.validateField('editorContent');
				} else {
					this.$refs.editorContent.clearValidate();
				}
			},
			choiceVideo() {
				uni.chooseVideo({
					count: 1,
					success: res => {
						if (res.errMsg == 'chooseVideo:ok') {
							let video = document.createElement('video');
							video.setAttribute('crossOrigin', 'anonymous'); //处理跨域
							video.setAttribute('src', res.tempFilePath);
							video.setAttribute('preload', 'auto');
							video.currentTime = 1;
							video.addEventListener('loadeddata', () => {
								let canvas = document.createElement('canvas'),
									width = video.videoWidth, //canvas的尺寸和图片一样
									height = video.videoHeight;

								const adjustRatio = 600;
								if (width > adjustRatio && width > height) {
									height = parseInt(height / (width / adjustRatio));
									width = adjustRatio;
								} else if (height > adjustRatio) {
									width = parseInt(width / (height / adjustRatio));
									height = adjustRatio;
								}

								canvas.width = width;
								canvas.height = height;
								canvas.getContext('2d').drawImage(video, 0, 0, width,
								height); //绘制canvas

								this.video = {
									poster: URL.createObjectURL(this.pngBase64ToBlob(canvas
										.toDataURL('image/png'))),
									posterWidth: width,
									posterHeight: height,
									width: video.videoWidth,
									height: video.videoHeight,
									size: res.size,
									duration: video.duration,
									url: res.tempFilePath,
									name: res.name
								};
							});
						}
					}
				});
			},
			
			playVideo(url) {
				this.isVideo = true;
				this.videoDialog = true;
				this.playerOptions.sources[0].type = 'video/mp4';
				this.playerOptions.sources[0].src = url;
			},
			dialogOpen() {
				if (this.$refs.videoPlayer) {
					this.$refs.videoPlayer.$el.children[0].children[0].currentTime = 0;
				}
			},
			dialogOpened() {
				this.$refs.videoPlayer.player.play();
			},
			dialogClosed() {
				this.$refs.videoPlayer.player.pause();
				this.isVideo = false;
			},
			posterDelete() {
				this.video = {};
			},
			imgUpload() {
				this.$refs.validImg.clearValidate();
			},
			imgDelete(e) {
				this.form.imageValue.splice(this.form.imageValue.findIndex(x => x.url == e.tempFilePath), 1);
				if (this.form.imageValue.length <= 0) {
					this.$refs.ruleForm.validateField('imageValue');
				}
			},
			imgMove(e) {
				this.form.imageValue = e;
			},
			pngBase64ToBlob(base64) {
				try {
					var arr = base64.split(',');
					var mime = arr[0].match(/:(.*?);/)[1] || 'image/png';
					// 去掉url的头，并转化为byte
					var bytes = window.atob(arr[1]);
					// 处理异常,将ascii码小于0的转换为大于0
					var ab = new ArrayBuffer(bytes.length);
					// 生成视图（直接针对内存）：8位无符号整数，长度1个字节
					var ia = new Uint8Array(ab);
			
					for (var i = 0; i < bytes.length; i++) {
						ia[i] = bytes.charCodeAt(i);
					}
			
					return new Blob([ab], {
						type: mime
					});
				} catch (e) {
					var ab = new ArrayBuffer(0);
					return new Blob([ab], {
						type: 'image/png'
					});
				}
			},
			secToTime(s) {
				var t = '00:00:00';
				if (s > -1) {
					t = '';
					var hour = Math.floor(s / 3600);
					var min = Math.floor(s / 60) % 60;
					var sec = s % 60;
					if (hour > 0) {
						t = hour.toString().padStart(2, '0') + ':';
					}

					t += min.toString().padStart(2, '0') + ':';
					t += parseInt(sec.toString().padStart(2, '0'));
				}
				return t;
			}
		}
	};
</script>

<style>
	.video {
		width: 140px;
		height: 140px;
		border-radius: 5px;
		border: 1px solid #eee;
	}

	.video:hover .icon24gf-play {
		transform: scale(1.2);
	}

	.video:hover .iconbofang {
		transform: scale(1.1);
	}

	.iconbofang {
		top: 0;
		right: 0;
		left: 0;
		bottom: 0;
		margin: auto;
		font-size: 34px;
		width: 34px;
		height: 34px;
		line-height: 34px;
		background-color: rgba(0, 0, 0, 0.9);
		border-radius: 50%;
		color: #bbb;
		transition: transform 0.2s;
	}

	.icon24gf-play {
		width: 46px;
		height: 46px;
		font-size: 46px;
		line-height: 46px;
		color: #eee;
		transition: transform 0.2s;
	}

	.del_btn_box {
		top: 5px;
		right: 5px;
		height: 26px;
		width: 26px;
		border-radius: 50%;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 2;
		transform: rotate(-45deg);
	}

	.del_btn {
		width: 15px;
		height: 2px;
		background-color: #fff;
		border-radius: 2px;
	}

	.del_btn:last-child {
		transform: rotate(90deg);
	}

	.duration {
		color: #fff;
		font-size: 13px;
		right: 8px;
		bottom: 8px;
	}

	.video_dialog>>>.el-dialog {
		border-radius: 10px;
		overflow: hidden;
	}
	
	.video_dialog>>>.el-dialog__header {
		padding: 16px;
	}
	
	.video_dialog>>>.el-dialog__headerbtn {
		top: 12px;
		right: 16px;
	}
	
	.video_dialog>>>.el-dialog__headerbtn {
		top: 10px;
		right: 16px;
	}
	
	.video_dialog>>>.el-dialog__body {
		padding: 0;
	}
</style>
